# 导入easyocr
import easyocr
import pandas as pd
import pyautogui as pag


# 创建reader对象
# 'ch_sim',
def extract_by_ocr(image_path):
    reader = easyocr.Reader(['en'], model_storage_directory=r"E:\Tech\easyocr_models")
    # 读取图像
    result = reader.readtext(image_path, allowlist ='0123456789')
    # 结果
    # print(result)
    return result


def detect_current_map_pos():
    x_image_path = '../images/map_coor/coor_x.png'
    y_image_path = '../images/map_coor/coor_y.png'
    coor_x = (586, 29, 24, 15)
    screenshot = pag.screenshot(region=coor_x)
    screenshot.save(x_image_path, quality=95)
    x_result = extract_by_ocr(x_image_path)

    coor_y = (633, 29, 24, 15)
    screenshot = pag.screenshot(region=coor_y)
    screenshot.save(y_image_path, quality=95)
    y_result = extract_by_ocr(y_image_path)
    print("x_result:", x_result)
    print("y_result:", y_result)
    X = None
    Y = None
    if len(x_result) > 0:
        if x_result[0][2] > 0.6:
            X = int(x_result[0][1])
    if len(y_result) > 0:
        if y_result[0][2] > 0.6:
            Y = int(y_result[0][1])

    if X is not None and Y is not None:
        return (X, Y)
    else:
        return None


import pydirectinput as pdg


def click():
    pdg.mouseDown()
    pdg.mouseUp()


def detect():
    # result = detect()
    # print(result)
    pdg.moveTo(641, 555)
    pdg.click()

    df = pd.read_excel("data/coor.xlsx", converters={"X": int, "Y": int})
    result = detect_current_map_pos()
    print(result)
    if result is not None:
        Mx, My = result
        shift_ratio = int(455 / 15)
        for idx in df.index:
            row = df.loc[idx]

            # if Mx > row["X"]:
            mov_px = (row["Y"] - My) * shift_ratio
            print("mov_px:", mov_px)
            Px, Py = pdg.position()
            pdg.moveTo(Px + mov_px, Py)
            click()
            break


import torch


def use_torch():
    x = torch.Tensor([1,2,3])
    x = x.to("cuda")


if __name__ == "__main__":
    # use_torch()
    x_image_path = '../images/map_coor/coor_x.png'
    y_image_path = '../images/map_coor/coor_y.png'
    coor_x = (586, 29, 24, 15)
    # screenshot = pag.screenshot(region=coor_x)
    # screenshot.save(x_image_path, quality=95)
    x_result = extract_by_ocr(x_image_path)
    y_result = extract_by_ocr(y_image_path)
    print("x_result:", x_result)
    print("y_result:", y_result)